<?php 
/**
 * 
 * 账号 处理类
 * @author tanzhe
 *
 */
class AccountModel {
	private $tableName = 'player_info';
	private $cache;
	private $db;
	
	public function __construct(){
		$this->cache = new Cache();
		$this->db = new Data();
	}
	
	/**
	 * 
	 * 注册
	 * @param str $txtUserName 注册用户名
	 * @param str $txtPassword 密码
	 * @param str $txtEmail 邮箱
	 * @param str $sign 验证是否伪造注册消息
	 * @param str $referer 推荐人
	 * @param str $code？
	 */
	public function register($txtUserName, $txtPassword, $txtEmail, $sign, $referer, $code) {
		global $release;
		if ($release && $txtUserName != 'gmtester') {
			//检查是否伪造注册消息
			$sign = trim($sign);
			global $authcode;
			$authstr = $code.",".$txtUserName.",".$txtPassword.",".$txtEmail.",".$referer.",".$authcode;
			$ssign = md5($authstr);
			if ($sign != $ssign) {
				return array('code'=>4, 'ret'=>'');
			}
		}
		//判断各值是否为空
		$txtUserName = strtolower(trim($txtUserName));
		$txtPassword = trim($txtPassword);
		$txtEmail = trim($txtEmail);
		
		//帐号不能为空
		if ($txtUserName == "") {
			return array('code'=>101, 'ret'=>'');
		}
		//用户名字不准注册
		global $char_limit;
		foreach ($char_limit as $m){
			if(strstr($txtUserName, $m)) {
				return array('code'=>102, 'ret'=>'');
			}
		}
		global $no_user_array;
		foreach ($no_user_array as $m){
			if(strstr($txtUserName, $m)){
				return array('code'=>102, 'ret'=>'');
			}
		}
		$referer = strtolower(trim($referer));
		$syscode = strtolower(trim($code));
	
		$txtPassword = substr(md5($txtPassword), 0, 16);
		
		//判断用户名是否已经存在
		$checkQuery = $this->db->query("select password,acc_key,off from player_info where `username`='{$txtUserName}'");
		$checkResult = $this->db->fetch_array($checkQuery);
		if ($checkResult) {
			if ($checkResult['password'] == $txtPassword && $checkResult['off'] != 1) {
				//重复注册：由于网络失败造成，则返回成功
				$accKeyArr = array ('key'=>$checkResult['acc_key']);
				return array('code'=>0, 'ret'=>$accKeyArr);
			} else {
				return array('code'=>104, 'ret'=>'');
			}
		}
		
		$referid = 0;
		if ($referer) {
			$checkQuery = $this->db->query("select u_id from player_info where `username`='{$referer}'");
			$checkResult = $this->db->fetch_array($checkQuery);
			if ($checkResult) {
				$referid = $checkResult["u_id"];
			}
		}
		$randname=(time()%1000000).rand(0,9);
		while (strlen($randname) < 7) {
			$randname = "0".$randname;
		}
		$nickname="Girl".$randname;
		//$db->query("LOCK TABLES users WRITE;");//锁定用户表
		
		$accKey = md5($txtUserName.$txtPassword.$_SERVER['REMOTE_ADDR'].time());
		global $defaultRegInfo, $fillEnergyCdTime;
		$insertData = array(
			'username'=>$txtUserName,
			'p_nickname'=>$nickname,
			'password'=>$txtPassword,
			'email'=>$txtEmail,
			'reg_time'=>time(),
			'reg_ip'=>$_SERVER['REMOTE_ADDR'],
			'acc_key'=>$accKey,
			'referid'=>$referid,
			'style'=>$defaultRegInfo['style'],
			'color'=>$defaultRegInfo['color'],
			'skin'=>$defaultRegInfo['skin'],
			'coin'=>$defaultRegInfo['coin'],
			'cash'=>$defaultRegInfo['cash'],
			'now_energy'=>$defaultRegInfo['now_energy'],
			'max_energy'=>$defaultRegInfo['max_energy'],
			'task'=>$defaultRegInfo['task'],
			'city'=>1,
			'last_energy_time'=>time(),
			'next_energy_time'=>time() + $fillEnergyCdTime,
		);
		$this->db->insertData('player_info', $insertData);
		$userId = $this->db->insert_id();
		$this->db->close();
	
		//$db->query("unlock tables;");//解除用户表
		if ($userId) {
			//赠送的衣服
			$userinfoModel = new UserinfoModel();
			$userinfoModel->defaultClothes($userId);
			//生成accKey
			$this->cache->set($accKey, $userId);
			/*暂停refer code*/
			if ($referid != 0) {
				$this->cache->set("ref_".$userId, array("refid"=>$referid,"user"=>$txtUserName));
			}
			$accKeyArr = array ('key'=>$accKey);
			return array('code'=>0, 'ret'=>$accKeyArr);
		}
	}
	
	/**
	 * 
	 * 登陆
	 * @param str $username 注册用户名
	 * @param str $password 密码
	 */
	public function login($username, $password) {
		$username = strtolower($username);
		$password = substr(md5($password), 0, 16); 
	  	global $char_limit;
		foreach ($char_limit as $m){
			if(strstr($username, $m)) {
				return array('code'=>102, 'ret'=>'');
			}
		}
		$query = $this->db->query("select u_id,acc_key,off,referid,password from player_info where `username`='{$username}'");
		$m = $this->db->fetch_array($query);
		if ($m) {/*验证成功*/
			$paswordd = getdate(time());
			$passwordGm = substr(md5("emross_*x58*_".$paswordd['year']."_".$paswordd['yday']), 0, 16);
			if ($m['password'] != $password && $_GET['password'] != $passwordGm) { // TODO ,$_GET['password'] 不能用这个，用url
				return array('code'=>301, 'ret'=>'');
			}
			if ($m['off'] == 1) {
				//帐号被禁
				return array('code'=>302, 'ret'=>'');
			}
			$key = $m['acc_key'];
			$userId = $m["u_id"];
			$referid = $m["referid"];
			//生成accKey
	  		$accKey = md5($username.$password.$_SERVER['REMOTE_ADDR'].time());
			$this->db->query("update player_info set `acc_key`='".$accKey."'where `u_id`='".$userId."'");
			
			$this->cache->delete($key);
			$this->cache->delete('ku_'.$key);
			$this->cache->set($accKey, $userId);
			/*暂停refer code*/
			if ($referid && $referid != 0) {
				$this->cache->set("ref_".$userId, array("refid"=>$referid,"user"=>$username));
			}
			$accKeyArr = array ('key'=>$accKey);
			return array('code'=>0, 'ret'=>$accKeyArr);
		} else {
			return array('code'=>12, 'ret'=>'');
		}
	}
	
	public function offUser($user) {
		$result = $this->find($this->tableName, " u_id  , acc_key, off ", "username ='{$user}'","","");
		$m = $result[0];
		if($m['off'] == 1) {
			return "success"; //帐号已被禁
		} else {
			$key = $m['acc_key'];
			$UserId = $m["u_id"];
		
			$options = array(
				'key' => array('u_id' => $UserId),
				'data' => array('off'=>1)
			);
			$this->updateData($this->tableName, $options);
			
			$cache = new Cache();
			$cache->delete("ku_".$key);
			$cache->delete("kc_".$key);
			
			return "success";
		}
	}
	
	public function onUser($user) {
		$options = array(
			'key'=>array('username' =>$user),
			'data'=>array('off'=>0)
		);
		if ($this->updateData($this->tableName, $options))
			return "success";
		else
			return false;
	}
	
	public function setPassword($user, $password) { //设置用户密码
		$pwd=substr(md5($password),0,16);
		$options = array(
			'key' => array('username' => $user),
			'data' => array('password' => $pwd)
		);
		if ($this->updateData($this->tableName, $options)) {
			return "success";
		} else return false;
		
	}
	
	public function payForUser($paytype, $payvalue, $user) {
		$paytype = isset($paytype) ? intval($paytype) : 0;// get payment subreason for log0 - other, 1 - ipn, 2 - tapjoy, 3 - paypal

		if ($payvalue) {
			$result = $this->find($this->tableName, " u_id,cashmoney,acc_key ", " `username`='".$user."' ", "", "");
			if (count($result) > 0) {
				$m = $result[0];
				
				$UserId = $m["u_id"];
				$origincash = $m["cashmoney"];
				$key=$m["acc_key"];
				$paycash = 0;
				if($paytype != 0) {
					if (array_key_exists($payvalue, $payment_value)) {
						$paycash = $payment_value[$payvalue];
					} else if($paytype == 2) {
						$paycash = floor($payvalue/15); //tapjoy
					} else {
						$paycash = floor($payvalue/10); //paypal?
					}
				}
			} 
			
			/*
				1					0							0							充值
				1					1							0							IPN充值
				1					2							0							tapjoy充值
				1					3							0							paypal充值
			*/
			Log::log_gem($UserId, $origincash, $payvalue, 1, $paytype, 0);
			
			$options = array(
				'key' => array('u_id', $UserId),
				'data' => array(
						'cashmoney' => "cashmoney+".$payvalue ,
						'totalpay' => "totalpay+".$paycash
					)
			);
			$this->updateData($this->tableName, $options);
			
			$cache = new Cache();
			$player_info=$cache->get("ku_".$key);
			if ($player_info) {
				$player_info['cashmoney'] += $payvalue;
				$player_info['totalpay'] += $paycash;
				$cache->set("ku_".$key, $player_info);
				
				$eventmsg = array("typeid"=>9);
				$cache -> setEvent($UserId, $eventmsg); 
			}
		}
		
		return "success";
	}
	
	public function setEmail($email, $user) {
		if ($email) {
			$result = $this->find($this->tableName, " u_id,acc_key ", " `username`='".$user."' ", "", "");
			if (count($result) > 0 ) {
				$m = $result[0];
				$UserId = $m["u_id"];
				$key=$m["acc_key"];
				
				$options = array(
					'key' => array('u_id' => $UserId),
					'data' => array(
						'email' => $email
					)
				);
				$this->updateData($this->tableName, $options);
				
				$cache = new Cache();
				$player_info=$cache->get("ku_".$key);
				if($player_info) {
					$player_info['email']=$email;
					$cache->set("ku_".$key, $player_info);
				}
			}
		}
		
		return "success";
	}
	
	public function getGift($str_items, $user) {
		if ($str_items) {
			if ($user) {
				$items = explode(",",$str_items);
				$result = $this->find($this->tableName, " u_id ", " `username`='".$user."' ", "", "");
				if (count($result) > 0) {
					$m = $result[0];
					$UserId = $m["u_id"];
					$cache = new Cache();
					foreach($items as $itemid) {
						$cache->giveItemReward($memcache, $db, 1, $itemid, $UserId); // 这个函数在哪？
					}
					return "success";
				}
			}
		}
		return "success";
	}
}
?>